#include "ScreenshotWorker.h"
#include <QDir>
#include <QPixmap>
#include <unistd.h>
#include <fcntl.h>
#include <QDebug>
#include <QScreen>
#include <QGuiApplication>

ScreenshotWorker *ScreenshotWorker::getInstance()
{
    static ScreenshotWorker singleton{};
    return &singleton;
}

void ScreenshotWorker::init(QObject *app)
{
    g_app = app;
}

int ScreenshotWorker::screenshot()
{
    static int count = 0;

    /* 构建video路径 */
    QString path = "./screenshot";

    QDir dir;
    if (!dir.exists(path)) {
        if (!dir.mkpath(path)){
            qDebug()<<"create dir faile:"<<path;
            return -1;
        } else {
            qDebug()<<"create dir succeed:"<<path;
        }
    }

    QPixmap p = QPixmap::grabWidget((QObject *)g_app);
    p.save(QString("./screenshot/%1.png").arg(count), "png");

    count++;

    return 0;
}

int ScreenshotWorker::exportScreenshot()
{
    QStringList cmd;
    QString command;
    int status = -1;

    cmd << QString("cp /home/root/screenshot/* /run/media/sda*/screenshot -rf");
    command = cmd.join(";");
    qDebug()<<"export screenshot cmd:"<<command;

    status = system(command.toUtf8().data());
    if((status < 0) || (!WIFEXITED(status)) || (0 != WEXITSTATUS(status))) {
        qDebug()<<"export screenshot failed";
        return -1;
    }
    sync();
    sleep(1);

    return 0;
}

ScreenshotWorker::ScreenshotWorker()
{

}
